import axios from 'axios'
import store from '@/store'
import PsMessage from '@/components/message/index'
import { parseTime } from '@/utils'
import i18n from '@/lang'
import { Encrypt, Decrypt } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  headers: {
    'content-type': 'application/json'
  },
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

// request interceptor
// 防止多次请求
// let startRefreshTokenFlag = false
service.interceptors.request.use(
  async config => {
    // do something before request is sent
    config.headers['MerchantId'] = process.env.VUE_APP_ID
    config.headers['ProjectId'] = process.env.VUE_APP_PROJECTID
    config.headers['Language'] = i18n.locale
    const appInfo = store.getters.appInfo || {}
    if (!config.noAppId && appInfo.appID) {
      config.headers['Version'] = appInfo.version
      config.headers['UnionID'] = appInfo.channel
      config.headers['AppId'] = appInfo.appID
    }
    if (store.getters.token) {
      !config.isLogin && await store.dispatch('user/getToken').catch(() => {})
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    if (config.isEncrypt) {
      const encryptData = Encrypt(config.data)
      config.headers['Secure'] = 'web'
      config.headers['SecurityKey'] = encryptData.encryptKey
      config.encryptKey = encryptData.key
      if (config.method !== 'get') {
        config.headers['SecurityBody'] = encryptData.crc
        config.data = encryptData.encrypt
      }
    }
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    // do something with request error

    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    let data = response.data
    if (response.config.encryptKey) {
      data = Decrypt(response.data, response.config.encryptKey) || {}
    }
    const code = data?.code
    const offset = response.config.xzconfig?.offset
    if (code !== 200) {
      const exArr = [100429, 451]
      if (code === 100403) {
        // #unfinished 通知登录过去处理
        store.dispatch('user/resetUserInfo')
        store.dispatch('user/setCustomerConfirm', i18n.t('freeze'))
      } else if (code === 401) {
        store.dispatch('user/resetUserInfo')
        if (data.data?.sub_code === 100404) {
          store.dispatch('user/setLogoutConfirm', `${i18n.t('logout', { device: data.data.sub_msg, time: parseTime(data.data.ts * 1000, '{y}/{m}/{d} {h}:{i}') })}`)
        }
      } else if (!exArr.includes(code) && !response.config.noMsg) {
        PsMessage({ offset, message: data.msg || i18n.t('serviceError') })
      }
      return Promise.reject(data)
    } else {
      return data
    }
  },
  error => {
    if (!error.config.noMsg) {
      if (error.message === 'Network Error') {
        PsMessage({ message: i18n.t('networkError') })
      } else {
        PsMessage({ message: error.msg || i18n.t('serviceError') })
      }
    }
    return Promise.reject(error)
  }
)

export default service
